/*
Copyright 2011 Mohit Shah
    
This file is part of SoundBlogs.

SoundBlogs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SoundBlogs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SoundBlogs.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.application.soundblogs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class HomePage extends Activity {
	EditText keyword_edit;
	private String keyword = null;
	private String json_text = null;
	private int number = 0;
	private final static String EVENTS = "events";
	private final static String INIT = "init";
	private final static String KEYWORD = "keyword";
	private AsyncTask<Void,Integer,Void> postkeyword = null;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);		
		setContentView(R.layout.homepage);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
		ImageButton blog = (ImageButton) findViewById(R.id.blogbutton);
		blog.setOnClickListener(new blog_click());
		ImageButton search = (ImageButton) findViewById(R.id.searchbutton);
		search.setOnClickListener(new search_click());
		keyword_edit = (EditText) findViewById(R.id.keyword);
	}
	
	private void taskfinished() {
		Intent intent = new Intent(HomePage.this,SearchMap.class);
		intent.putExtra(INIT,number);
		intent.putExtra(EVENTS,json_text);
		intent.putExtra(KEYWORD, keyword);
		HomePage.this.startActivity(intent);			

	}
	private void postData() throws JSONException{
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://soundblogs.org/search.php");
		JSONObject json = new JSONObject();

		try {
			// JSON data:
			
			json.put("keyword", keyword);
			JSONArray postjson=new JSONArray();
			postjson.put(json);
			Log.d("JSONPost","JSON Array Built");

			// Post the data:
			httppost.setHeader("json",json.toString());
			httppost.getParams().setParameter("jsonpost",postjson);

			// Execute HTTP Post Request
			System.out.print(json);
			HttpResponse response = httpclient.execute(httppost);
			Log.d("JSONPost","JSON Post Executed");

			// for JSON:
			if(response != null)
			{
				InputStream is = response.getEntity().getContent();

				BufferedReader reader = new BufferedReader(new InputStreamReader(is));
				StringBuilder sb = new StringBuilder();

				String line = null;
				try {
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				Log.d("JSONPost",sb.toString());
				json_text = new String(sb.toString());
			}

		}catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
    		// TODO Auto-generated catch block
    	}
		taskfinished();
	}
	
	
	private class blog_click implements View.OnClickListener{
		@Override
		public void onClick(View v){
			Intent intent = new Intent(HomePage.this,ChooseAudio.class);
			HomePage.this.startActivity(intent);
		}
		
	};
	private class search_click implements View.OnClickListener{
		@Override
		public void onClick(View v){
			Toast.makeText(getApplicationContext(), "Retrieving Data...Please Wait", Toast.LENGTH_LONG).show();
			keyword = new String(((keyword_edit.getText().toString()).toLowerCase()).trim());
			postkeyword = new PostKeyword().execute();
		}
		
	};
    private class PostKeyword extends AsyncTask<Void,Integer,Void> {
    	@Override
    	public Void doInBackground(Void... params){
    		Void ret = null;
			try {
				postData();
			}
			catch (JSONException j) {
				Log.d("JSONPost","Failed");
			}
    		return ret;
    	}
    }

}
